<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller as BaseContoller;
use App\Http\Requests\LoginRequest;
use App\Http\Responses\CustomResponse;
use App\Services\admin\AdminUserService;
use Illuminate\Http\Request;

/**
 * 登录
 * class IndexController
 */
class LoginController extends BaseContoller
{
    /**
     * 登录页
     *
     * @return void
     */
    public function index(Request $request)
    {
        return view('admin.login.login');
    }

    /**
     * 登录
     *
     * @param  Request  $request
     * @return void
     */
    public function login(LoginRequest $request)
    {
        $data = $request->all();
        if ($request->isMethod('POST')) {
            $user = AdminUserService::checkLogin($request->all());
            //判断用户信息
            if (! $user) {
                return CustomResponse::fail('用户不存在');
            }
            if (password_verify($data['password'], $user->password) === false) {
                return CustomResponse::fail('密码错误');
            }
            if ($user->status != 1) {
                return CustomResponse::fail('账号已被锁定');
            }
            if (! isset($user->roles)) {
                return CustomResponse::fail('当前用户没有权限，请联系管理员');
            }

            $request->session()->put(config('amis.cache.login_user'), json_encode($user));

            // 更新登录信息
            $userResult = AdminUserService::edit($user->id, [
                'login_time' => date('Y-m-d H:i:s'),
                'login_ip' => $request->ip(),
            ]);
            $result = AdminUserService::addLoginlog($user->id, $user->name, $request->userAgent(), $request->ip(), 1);

            if ($result && $userResult) {
                return CustomResponse::ok();
            } else {
                return CustomResponse::fail('登录失败');
            }
        }
    }

    /**
     * 退出登录
     * User: zhx
     * Date: 2023/6/26 9:55
     */
    public function logout(Request $request)
    {
        $request->session()->flush();

        return redirect(config('amis.tpl.admin_login_page'));
    }
}
